package cn.wei.sdd.core.service.impl;

import cn.wei.sdd.core.enums.TakeMoneyStatusEnum;
import cn.wei.sdd.core.enums.TransStatusEnum;
import cn.wei.sdd.core.mapper.TransFlowMapper;
import cn.wei.sdd.core.mapper.UserAccountMapper;
import cn.wei.sdd.core.pojo.entity.TakeMoneyRecord;
import cn.wei.sdd.core.mapper.TakeMoneyRecordMapper;
import cn.wei.sdd.core.pojo.entity.TransFlow;
import cn.wei.sdd.core.pojo.entity.User;
import cn.wei.sdd.core.pojo.entity.UserAccount;
import cn.wei.sdd.core.pojo.query.TakeMoneyQuery;
import cn.wei.sdd.core.pojo.vo.CheckTakeMoneyVO;
import cn.wei.sdd.core.pojo.vo.TakeMoneyRecordByUserIdVO;
import cn.wei.sdd.core.pojo.vo.takeMoneyVO;
import cn.wei.sdd.core.service.TakeMoneyRecordService;
import cn.wei.sdd.core.service.UserAccountService;
import cn.wei.sdd.core.utils.NoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 提现记录表 服务实现类
 * </p>
 *
 * @author Wei
 * @since 2021-11-10
 */
@Service
public class TakeMoneyRecordServiceImpl extends ServiceImpl<TakeMoneyRecordMapper, TakeMoneyRecord> implements TakeMoneyRecordService {

    @Resource
    private TransFlowMapper transFlowMapper;

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private UserAccountService userAccountService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void takeMoney(takeMoneyVO takeMoneyVO, Long userId, Long userType) {

        //添加提现记录
        TakeMoneyRecord takeMoneyRecord = new TakeMoneyRecord();
        takeMoneyRecord.setOutTradeNo(NoUtils.getTakeMoneyNo());
        takeMoneyRecord.setUserId(userId);
        takeMoneyRecord.setUserType(Math.toIntExact(userType));
        takeMoneyRecord.setUserName(takeMoneyVO.getUserName());
        takeMoneyRecord.setZfbAccount(takeMoneyVO.getZfbAccount());
        takeMoneyRecord.setTotalAmount(takeMoneyVO.getTotalAmount());
        takeMoneyRecord.setStatus(TakeMoneyStatusEnum.TAKE_ING.getStatus());
        baseMapper.insert(takeMoneyRecord);

        //添加流水
        TransFlow transFlow = new TransFlow();
        transFlow.setUserType(userType);
        transFlow.setUserId(userId);
        transFlow.setTransNo(NoUtils.getTransNo());
        transFlow.setUserName(takeMoneyVO.getUserName());
        transFlow.setTransType(TransStatusEnum.DRAW.getStatus());
        transFlow.setTransTypeName(TransStatusEnum.DRAW.getMsg());
        transFlow.setTransAmount(takeMoneyVO.getTotalAmount());
        transFlow.setMemo("申请提现：申请编号"+takeMoneyRecord.getOutTradeNo());
        transFlowMapper.insert(transFlow);

        //扣除余额
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper.eq("user_type",userType)
                .eq("user_id",userId);

        //更新用户账户
        UserAccount account = userAccountMapper.selectOne(userAccountQueryWrapper);

        UserAccount userAccount = new UserAccount();
        //获取原有金额
        BigDecimal amount = account.getAmount();
        userAccount.setId(account.getId());
        //原有金额-订单金额
        amount = amount.subtract(takeMoneyVO.getTotalAmount());
        userAccount.setAmount(amount);
        userAccountMapper.updateById(userAccount);
    }

    @Override
    public IPage<TakeMoneyRecord> listPage(Page<TakeMoneyRecord> pageParam, TakeMoneyQuery takeMoneyQuery) {
        if (takeMoneyQuery==null){
            return baseMapper.selectPage(pageParam,null);
        }
        Integer userType = takeMoneyQuery.getUserType();
        String userName = takeMoneyQuery.getUserName();
        String zfbAccount = takeMoneyQuery.getZfbAccount();
        Integer status = takeMoneyQuery.getStatus();

        System.out.println("userName:"+userName);
        System.out.println("zfbAccount:"+zfbAccount);

        QueryWrapper<TakeMoneyRecord> takeMoneyRecordQueryWrapper = new QueryWrapper<>();
        //eq()有个重载方法，如果前面的为true，就组装后面的条件
        takeMoneyRecordQueryWrapper
                .eq(userType!=null,"user_type",userType)
                .eq(userName!=null&& !userName.isEmpty(),"user_name",userName)
                .eq(zfbAccount!=null&& !zfbAccount.isEmpty(),"zfb_account",zfbAccount)
                .eq(status!=null,"status",status);

        return baseMapper.selectPage(pageParam,takeMoneyRecordQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examineTakeMoney(CheckTakeMoneyVO checkTakeMoneyVO, String userName) {

        String outTradeNo = checkTakeMoneyVO.getOutTradeNo();
        Integer status = checkTakeMoneyVO.getStatus();
        String memo = checkTakeMoneyVO.getMemo();

        //获取提现对象
        QueryWrapper<TakeMoneyRecord> moneyRecordQueryWrapper = new QueryWrapper<>();
        moneyRecordQueryWrapper.eq("out_trade_no",outTradeNo);
        TakeMoneyRecord takeMoneyRecord = baseMapper.selectOne(moneyRecordQueryWrapper);

        //修改信息
        TakeMoneyRecord moneyRecord = new TakeMoneyRecord();
        moneyRecord.setStatus(status);
        moneyRecord.setChecker(userName);
        moneyRecord.setMemo(memo);
        baseMapper.update(moneyRecord,moneyRecordQueryWrapper);

        //提现失败，1退钱到账户，2添加流水

        if (status==TakeMoneyStatusEnum.TAKE_ERROR.getStatus()){
            // 1、退钱到账户
            //获取账户金额
            Long userId = takeMoneyRecord.getUserId();
            Integer userType = takeMoneyRecord.getUserType();
            BigDecimal amount = userAccountService.getAmountByUidAndUType(userId, userType);

            //更新账户信息
            UpdateWrapper<UserAccount> userAccountUpdateWrapper = new UpdateWrapper<>();
            //设置余额：当前余额+提现失败余额
            amount = amount.add(takeMoneyRecord.getTotalAmount());
            userAccountUpdateWrapper
                    .eq("user_id",userId)
                    .eq("user_type",userType)
                    .set("amount",amount);
            userAccountMapper.update(null,userAccountUpdateWrapper);

            //2、添加流水
            TransFlow transFlow = new TransFlow();
            transFlow.setUserType(Long.valueOf(userType));
            transFlow.setUserId(userId);
            transFlow.setTransNo(NoUtils.getTransNo());
            transFlow.setUserName(takeMoneyRecord.getUserName());
            transFlow.setTransType(TransStatusEnum.REFUND.getStatus());
            transFlow.setTransTypeName(TransStatusEnum.REFUND.getMsg());
            transFlow.setTransAmount(takeMoneyRecord.getTotalAmount());
            transFlow.setMemo(TransStatusEnum.REFUND.getMsg()+"，订单号："+takeMoneyRecord.getOutTradeNo());
            transFlowMapper.insert(transFlow);

        }

    }

    @Override
    public TakeMoneyRecord findOneByTradeCode(String out_trade_no) {
        QueryWrapper<TakeMoneyRecord> takeMoneyRecordQueryWrapper = new QueryWrapper<>();
        takeMoneyRecordQueryWrapper.eq("out_trade_no",out_trade_no);

        return baseMapper.selectOne(takeMoneyRecordQueryWrapper);
    }

    @Override
    public List<TakeMoneyRecordByUserIdVO> getTakeMoneyListByUserId(Long userId) {
        List<TakeMoneyRecordByUserIdVO> myTakeMoneyRecord = baseMapper.getMyTakeMoneyRecord(userId);
        ArrayList<TakeMoneyRecordByUserIdVO> list = new ArrayList<>();
        for (TakeMoneyRecordByUserIdVO record : myTakeMoneyRecord) {
//            状态（-1：提现失败，0：审核中，1：打款中，2：提现成功）
            String status = record.getStatus();

            if(status.equals(""+TakeMoneyStatusEnum.TAKE_ING.getStatus())){

                record.setStatus(TakeMoneyStatusEnum.TAKE_ING.getMsg());
            }
            if(status.equals(""+TakeMoneyStatusEnum.TAKE_PAY.getStatus())){
                record.setStatus(TakeMoneyStatusEnum.TAKE_PAY.getMsg());
            }
            if(status.equals(""+TakeMoneyStatusEnum.TAKE_SUCCESS.getStatus())){
                record.setStatus(TakeMoneyStatusEnum.TAKE_SUCCESS.getMsg());
            }
            if(status.equals(""+TakeMoneyStatusEnum.TAKE_ERROR.getStatus())){
                System.out.println(record.getStatus().equals(TakeMoneyStatusEnum.TAKE_ERROR.getStatus()));
                record.setStatus(TakeMoneyStatusEnum.TAKE_ERROR.getMsg());
            }
            System.out.println(record);
            list.add(record);
        }
        return list;
    }

    @Override
    public BigDecimal getTakeMoneyCount() {
        return baseMapper.totalAmountSum();
    }
}
